package com.zzyl.framework.interceptor;

import com.zzyl.common.utils.StringUtils;
import com.zzyl.common.utils.UserThreadLocal;
import com.zzyl.framework.web.service.TokenService;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.apache.hc.core5.http.HttpHeaders;
import org.apache.hc.core5.http.HttpStatus;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * TODO
 *
 * @Author Yjr
 * @Date 2025/5/25 9:23
 */
@Slf4j
@Component
public class MemberInterceptor implements HandlerInterceptor {
    @Autowired
    private TokenService tokenService;

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserThreadLocal.remove();
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        if (!(handler instanceof HandlerMethod)){
            return true;
        }

        //查看是否携带token
        String token = request.getHeader(HttpHeaders.AUTHORIZATION);
        if (StringUtils.isBlank(token)){
            log.error("未携带token,拦截!");
            response.setStatus(HttpStatus.SC_UNAUTHORIZED);
            return false;
        }

        //查看token是否合法
        try {
            Claims claims = tokenService.parseToken(token);
            Object userIdObject = claims.get("userId");
            Long userId = Long.valueOf(String.valueOf(userIdObject));
            UserThreadLocal.set(userId);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("token不合法,拦截!");
            response.setStatus(HttpStatus.SC_UNAUTHORIZED);
            return false;
        }

        //合法放行
        return true;
    }
}
